package com.sixth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.wxpay.sdk.WXPayUtil;
import com.sixth.core.entity.*;
import com.sixth.core.vo.R;
import com.sixth.mapper.*;
import com.sixth.service.OrderBackfeeService;
import com.sixth.util.HttpClient;
import com.sixth.vo.OrderChargeItemVo;
import com.sixth.vo.OrderChargeVo;
import com.sixth.vo.OrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.sixth.util.OrderUtil.backPlatformId;
import static com.sixth.util.OrderUtil.getOrderNoBackFeeNo;

/**
 * @program: sixth-hospital-parent
 * @description:
 * @author: 李劲锋
 * @create: 2024-08-19 15:33
 **/
@Service
public class OrderBackfeeServiceImpl extends ServiceImpl<OrderBackfeeMapper, OrderBackfee> implements OrderBackfeeService {
    @Autowired
    private OrderBackfeeMapper orderBackfeeMapper;
    @Autowired
    private OrderBackfeeItemMapper orderBackfeeItemMapper;
    @Autowired
    private CareOrderItemMapper careOrderItemMapper;
    @Autowired
    private OrderChargeMapper orderChargeMapper;
    @Autowired
    private OrderChargeItemMapper orderChargeItemMapper;
    @Autowired
    private CareOrderMapper careOrderMapper;

    @Override
    public R<List<CareHistory>> selectByIdFee(String registrationId) {
        List<CareHistory> list = orderBackfeeMapper.selectByIdAllFee(registrationId);
        return R.ok(list);
    }


    @Override
    public R orderBackFee(OrderChargeVo orderChargeVo) {
        // 创建现金退费订单
        OrderBackfee orderBackfee = new OrderBackfee();
        orderBackfee.setBackId(getOrderNoBackFeeNo()); // 生成唯一退费ID
        orderBackfee.setBackAmount(BigDecimal.valueOf(orderChargeVo.getOrderAmount())); // 退费金额
        orderBackfee.setChId(orderChargeVo.getChId()); // 病例ID
        orderBackfee.setRegId(orderChargeVo.getRegId()); // 挂号ID
        orderBackfee.setPatientName(orderChargeVo.getPatientName()); // 患者姓名
        orderBackfee.setBackStatus("1"); // 退费状态
        orderBackfee.setBackType("0");

        // 检查 orderIds 是否不为空且不为 null
        if (orderChargeVo.getOrderIds() != null && !orderChargeVo.getOrderIds().isEmpty()) {
            String orderId = orderChargeVo.getOrderIds().get(0);
            orderBackfee.setOrderId(orderId);
        } else {
            orderBackfee.setOrderId(null); // 如果没有 orderIds 则设置为 null
        }

        orderBackfee.setBackPlatformId(backPlatformId());
        orderBackfee.setBackTime(new Date());
        orderBackfee.setCreateTime(new Date());
        orderBackfee.setCreateBy(orderChargeVo.getCreateBy());
        orderBackfeeMapper.insert(orderBackfee);

        // 修改his_care_order_item表的状态
        List<String> itemIds = orderChargeVo.getOrderChargeItemDtoList().stream()
                .map(OrderChargeItemVo::getItemId)
                .collect(Collectors.toList());

        QueryWrapper<CareOrderItem> careOrderItemQuery = new QueryWrapper<>();
        careOrderItemQuery.in("item_id", itemIds);
        CareOrderItem careOrderItem = new CareOrderItem();
        careOrderItem.setStatus("2");
        careOrderItemMapper.update(careOrderItem, careOrderItemQuery);

        // 修改his_order_charge_item表的状态
        QueryWrapper<OrderChargeItem> orderChargeQuery =  new QueryWrapper<>();
        orderChargeQuery.in("item_id", itemIds);
        OrderChargeItem orderChargeItem = new OrderChargeItem();
        orderChargeItem.setStatus("2");
        orderChargeItemMapper.update(orderChargeItem, orderChargeQuery);


        // 写入退费订单详情表
        List<OrderBackfeeItem> orderBackfeeItemList = orderChargeVo.getOrderChargeItemDtoList().stream()
                .map(orderChargeItemVo -> {
                    OrderBackfeeItem orderBackfeeItem = new OrderBackfeeItem();
                    orderBackfeeItem.setCoId(orderChargeItemVo.getCoId());
                    orderBackfeeItem.setItemAmount(BigDecimal.valueOf(orderChargeItemVo.getItemAmount()));
                    orderBackfeeItem.setItemId(orderChargeItemVo.getItemId());
                    orderBackfeeItem.setItemName(orderChargeItemVo.getItemName());
                    orderBackfeeItem.setItemNum(BigDecimal.valueOf(orderChargeItemVo.getItemNum()));
                    orderBackfeeItem.setItemPrice(orderChargeItemVo.getItemPrice());
                    orderBackfeeItem.setItemType(orderChargeItemVo.getItemType());
                    orderBackfeeItem.setStatus("2");
                    orderBackfeeItem.setBackId(orderBackfee.getBackId());
                    orderBackfeeItemMapper.insert(orderBackfeeItem);
                    return orderBackfeeItem;
                })
                .collect(Collectors.toList());

        Map<String, Object> result = new HashMap<>();
        result.put("BackId", orderBackfee.getBackId());
        result.put("backAmount", orderBackfee.getBackAmount());
        result.put("orderBackfeeItemList", orderBackfeeItemList);

        return R.ok(result);
    }

    @Override
    public R<IPage<OrderBackfee>> selectByPage(OrderVo orderVo) {
        IPage<OrderBackfee> page = new Page<>(orderVo.getPageNum(), orderVo.getPageSize());
        QueryWrapper<OrderBackfee> wrapper = new QueryWrapper<>();

        // 检查并添加查询条件
        if (orderVo.getRegId() != null && !orderVo.getRegId().trim().isEmpty()) {
            wrapper.eq("reg_id", orderVo.getRegId().trim());
        }
        if (orderVo.getPatientName() != null && !orderVo.getPatientName().trim().isEmpty()) {
            wrapper.eq("patient_name", orderVo.getPatientName().trim());
        }

        // 按照 create_time 字段倒序排序
        wrapper.orderByDesc("create_time");

        IPage<OrderBackfee> orderIPage = orderBackfeeMapper.selectPage(page, wrapper);
        return R.ok(orderIPage);
    }
    // 微信退费

    @Value("${weixin.appid}")
    private String appid;
    @Value("${weixin.mch_id}")
    private String mch_id;
    @Value("${weixin.api_key}")
    private String api_key;
    @Override
    public R createRefundWx(OrderChargeVo orderChargeVo) {

        QueryWrapper<OrderCharge> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("order_id", orderChargeVo.getOrderIds());  // 使用 in 进行查询
        OrderCharge order = orderChargeMapper.selectOne(queryWrapper);

        if (order == null) {
            return R.error("订单不存在");
        }


        if (!"1".equals(order.getOrderStatus())) {
            return R.error("订单未支付或已经退款");
        }

        String refundOrderId = getOrderNoBackFeeNo(); // 生成唯一退款订单号
        Map<String, String> params = new HashMap<>();
        params.put("appid", appid);
        params.put("mch_id", mch_id);
        params.put("nonce_str", WXPayUtil.generateNonceStr());
        params.put("out_trade_no", String.join(",", orderChargeVo.getOrderIds())); // 用逗号连接所有订单ID
        params.put("out_refund_no", refundOrderId);
        params.put("total_fee", new BigDecimal(orderChargeVo.getOrderAmount()).multiply(new BigDecimal(100)).longValue() + "");
        params.put("refund_fee", new BigDecimal(0.01).multiply(new BigDecimal(100)).toBigInteger().toString());
        params.put("notify_url", "http://localhost:8080/handleBackfeeWithWx/back");

        try {
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
            client.setHttps(true);
            client.setXmlParam(WXPayUtil.generateSignedXml(params, api_key));
            client.post();
            String content = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(content);

            if ("SUCCESS".equals(resultMap.get("return_code"))) {
                // 退款成功后，调用 orderBackFee 方法
                return orderBackFee(orderChargeVo);
            } else {
                return R.error("退款申请失败：" + resultMap.get("err_code_des"));
            }
        } catch (Exception e) {
            return R.error("退款请求异常: " + e.getMessage());
        }
    }

    @Override
    public R dispensingStatus(OrderChargeVo orderChargeVo) {
        // 修改his_care_order_item表的状态
        List<String> itemIds = orderChargeVo.getOrderChargeItemDtoList().stream()
                .map(OrderChargeItemVo::getItemId)
                .collect(Collectors.toList());

        QueryWrapper<CareOrderItem> careOrderItemQuery = new QueryWrapper<>();
        careOrderItemQuery.in("item_id", itemIds);
        CareOrderItem careOrderItem = new CareOrderItem();
        careOrderItem.setStatus("3");
        careOrderItemMapper.update(careOrderItem, careOrderItemQuery);

        // 修改his_order_charge_item表的状态
        QueryWrapper<OrderChargeItem> orderChargeQuery =  new QueryWrapper<>();
        orderChargeQuery.in("item_id", itemIds);
        OrderChargeItem orderChargeItem = new OrderChargeItem();
        orderChargeItem.setStatus("3");
        orderChargeItemMapper.update(orderChargeItem, orderChargeQuery);
        return R.ok(200);
    }

    @Override
    public R orderClientBackFee(List<String> orderIds) {
        // 用循环方式，拿到orderChargeItemMapper里的金额
        BigDecimal totalAmount = null;
        for (String itemId : orderIds) {
            QueryWrapper<OrderChargeItem> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("item_id", itemId);
            List<OrderChargeItem> orderChargeItemList = orderChargeItemMapper.selectList(queryWrapper);
            totalAmount = orderChargeItemList.stream()
                    .map(OrderChargeItem::getItemAmount)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            //调用退费方法，传入订单ID和总金额
        }
        // 拿到itemId，去orderChargeItemMapper查询coId
        QueryWrapper<OrderChargeItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("item_id", orderIds);
        List<OrderChargeItem> orderChargeItemList = orderChargeItemMapper.selectList(queryWrapper);
        String orderId = orderChargeItemList.get(0).getOrderId();

        QueryWrapper<OrderCharge> orderChargeQuery = new QueryWrapper<>();
        orderChargeQuery.eq("order_id", orderId);
        OrderCharge orderCharge = orderChargeMapper.selectOne(orderChargeQuery);

        // 写入orderBackfee表
        OrderBackfee orderBackfee = new OrderBackfee();
        orderBackfee.setBackId(getOrderNoBackFeeNo());
        orderBackfee.setBackAmount(totalAmount);
        orderBackfee.setChId(orderCharge.getChId());
        orderBackfee.setRegId(orderCharge.getRegId());
        orderBackfee.setPatientName(orderCharge.getPatientName());
        orderBackfee.setBackStatus("1");
        orderBackfee.setBackType("2");
        orderBackfee.setOrderId(orderCharge.getOrderId());
        orderBackfee.setBackPlatformId(backPlatformId());
        orderBackfee.setCreateBy(orderCharge.getCreateBy());
        orderBackfee.setBackTime(new Date());
        orderBackfee.setCreateTime(new Date());
        orderBackfeeMapper.insert(orderBackfee);

        // 写入orderBackFeeItem,用循环的方式orderIds
        for (String itemId : orderIds) {
            OrderBackfeeItem orderBackfeeItem = new OrderBackfeeItem();
            QueryWrapper<OrderChargeItem> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("item_id", itemId);
            OrderChargeItem orderChargeItem = orderChargeItemMapper.selectOne(queryWrapper1);
            orderBackfeeItem.setItemId(itemId);
            orderBackfeeItem.setCoId(orderChargeItem.getCoId());
            orderBackfeeItem.setItemName(orderChargeItem.getItemName());
            orderBackfeeItem.setItemPrice(orderChargeItem.getItemPrice());
            orderBackfeeItem.setItemNum(orderChargeItem.getItemNum());
            orderBackfeeItem.setBackId(orderBackfee.getBackId());
            orderBackfeeItem.setItemAmount(orderChargeItem.getItemAmount());
            orderBackfeeItem.setItemType(orderChargeItem.getItemType());
            orderBackfeeItem.setStatus("2");
            orderBackfeeItemMapper.insert(orderBackfeeItem);
            // 修改his_care_order_item表的状态
            QueryWrapper<CareOrderItem> careOrderItemQuery = new QueryWrapper<>();
            careOrderItemQuery.in("item_id", orderIds);
            CareOrderItem careOrderItem = new CareOrderItem();
            careOrderItem.setStatus("2");
            careOrderItemMapper.update(careOrderItem, careOrderItemQuery);
            // 修改his_order_charge_item表的状态
            orderChargeQuery.in("item_id", orderIds);
            OrderChargeItem orderChargeItem1 = new OrderChargeItem();
            orderChargeItem1.setStatus("2");
            orderChargeItemMapper.update(orderChargeItem1, queryWrapper1);

        }

        return R.ok(orderCharge.getChId());
    }


}
